<template>
  <div ref="chartRef" :class="className" :style="{ height: height, width: width }" />
</template>

<script lang="ts" setup>
  import { onBeforeUnmount, onMounted, ref, watch } from 'vue';
  import UseCharts from '@/hooks/useCharts';

  const chartRef = ref();
  const { setOptions, destroy } = UseCharts(chartRef);
  const props = defineProps({
    className: {
      type: String,
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: String,
      default: '300px',
    },
    value: {
      type: Array<number>,
      default: [],
    },
  });

  onMounted(() => {
    initChart();
  });

  function initChart() {
    setOptions({
      tooltip: {
        trigger: 'axis',
      },
      xAxis: {
        type: 'category',
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          type: 'line',
          encode: {
            x: 'name',
            y: 'value',
          },
        },
      ],
    });
  }

  watch(
    () => props.value,
    (val) => {
      setOptions({
        dataset: {
          source: val,
        },
      });
    }
  );

  onBeforeUnmount(() => {
    destroy();
  });
</script>
